<?php


namespace apps\marriage\app\mp\controller;

use apps\marriage\core\logic\GoMessageLogic;
use apps\marriage\core\logic\SmsLogic;
use apps\marriage\core\logic\WeixinMpLogic;
use apps\marriage\core\service\MemberProfileService;
use apps\marriage\core\service\SiteConfigService;
use apps\marriage\core\service\UserPlatformService;
use apps\marriage\core\service\UserService;
use think\Exception;
use think\Request;

class UserController extends BaseMarriageMpController
{
    /**
     * @var UserService
     */
    private $userService;

    /**
     * @var MemberProfileService
     */
    private $memberProfileService;

    /**
     * @var UserPlatformService
     */
    private $userPlatformService;

    /**
     * @var SiteConfigService
     */
    private $siteConfigService;

    /**
     * @var SmsLogic
     */
    private $smsLogic;

    /**
     * @var WeixinMpLogic
     */
    private $weixinMpLogic;

    /**
     * @var GoMessageLogic
     */
    private $goMessageLogic;

    protected function init()
    {
        parent::init();
        $this->userService = service('User', SERVICE_NAMESPACE);
        $this->userPlatformService = service('UserPlatform', SERVICE_NAMESPACE);
        $this->smsLogic = logic('Sms', LOGIC_NAMESPACE);
        $this->siteConfigService = service('SiteConfig', SERVICE_NAMESPACE);
        $this->weixinMpLogic = logic('WeixinMp', LOGIC_NAMESPACE);
        $this->memberProfileService = service('MemberProfile', SERVICE_NAMESPACE);
        $this->goMessageLogic = logic('GoMessage', LOGIC_NAMESPACE);
    }

    public function login(Request $request)
    {
        $mobile = $request->param('mobile');
        $captcha = $request->param('sms_captcha');
        if(!check_mobile($mobile)) {
            throw new Exception('手机号错误');
        }
        if(!$this->smsLogic->verifyCaptcha('login', $mobile, $captcha)) {
            throw new Exception('短信验证码错误');
        }
        $user = $this->userService->getByMobile($mobile);
        if($user && $user['is_deleted'] == 0) {
            $user['access_token'] = $this->userService->genAccessToken($user);
            $user['upload_token'] = $this->userService->getUploadToken($user['id']);
        } else {
            throw new Exception('手机号不存在');
        }
        if($user['is_locked'] == 1) {
            throw new Exception('该账号已被锁定');
        }
        $appId = $this->siteConfigService->getValueByCode('weixin_mp_app_id');
        $userPlatform = $this->userPlatformService->getByUserIdWithAppid($appId, $user['id']);
        $user['openid'] = $userPlatform ? $userPlatform['open_id'] : '';
        if($userPlatform && $userPlatform['is_subscribed'] == 1) {
            $user['subscribe'] = true;
        } else {
            $user['subscribe'] = false;
        }

        $member = $this->memberProfileService->getByUserId($user['id']);
        $member = $this->memberProfileService->format($member);

        $user['gomessage_uid'] = $this->goMessageLogic->genUid($user['id']);

        return $this->success(['user' => $user, 'member' => $member]);
    }

    public function login_by_openid(Request $request)
    {
        $openid = $request->param('openid');
        $userDto = $this->userService->loginByOpenid($openid);
        if(!$userDto || $userDto['is_deleted'] == 1) {
            throw new Exception('账号不存在');
//            return $this->success([
//                'user' => null,
//                'member' => null
//            ]);
        }
        if($userDto['is_locked'] == 1) {
            throw new Exception('该账号已被锁定');
        }
        $userDto['openid'] = $openid;

        $userPlatform = $this->userPlatformService->getByOpenid($openid);
        if($userPlatform && $userPlatform['is_subscribed'] == 1) {
            $userDto['subscribe'] = true;
        } else {
            $userDto['subscribe'] = false;
        }

        $member = $this->memberProfileService->getByUserId($userDto['id']);
        $member = $this->memberProfileService->format($member);

        $userDto['gomessage_uid'] = $this->goMessageLogic->genUid($userDto['id']);

        return $this->success([
            'user' => $userDto,
            'member' => $member
        ]);
    }

    public function login_by_code(Request $request)
    {
        $code = $request->param('code');
        $res = $this->weixinMpLogic->getApiClient()->get_userinfo_by_authorize('snsapi_base');
        if($res[1]) {
            $res[1] = json_decode(json_encode($res[1]),TRUE);
            if(isset($res[1]['openid'])) {
                $openid = $res[1]['openid'];
                $userDto = $this->userService->loginByOpenid($openid);

                if(!$userDto || $userDto['is_deleted'] == 1) {
                    throw new Exception('账号不存在');
                }
                if($userDto['is_locked'] == 1) {
                    throw new Exception('该账号已被锁定');
                }
                $userDto['openid'] = $openid;

                $appId = $this->siteConfigService->getValueByCode('weixin_mp_app_id');
                $userPlatform = $this->userPlatformService->getByUserIdWithAppid($appId, $userDto['id']);
                if($userPlatform && $userPlatform['is_subscribed'] == 1) {
                    $userDto['subscribe'] = true;
                } else {
                    $userDto['subscribe'] = false;
                }

                $member = $this->memberProfileService->getByUserId($userDto['id']);
                $member = $this->memberProfileService->format($member);

                $userDto['gomessage_uid'] = $this->goMessageLogic->genUid($userDto['id']);

                return $this->success([
                    'user' => $userDto,
                    'member' => $member
                ]);
            } else {
                throw new Exception('发生错误');
            }
        } else {
            throw new Exception('发生错误');
        }
    }

    public function login_by_token(Request $request)
    {
        $accessToken = $request->param('access_token');
        $user = $this->userService->getAuth($accessToken);
        if(!$user || $user['is_deleted'] == 1) {
            throw new Exception('账号不存在');
        }
        if($user['is_locked'] == 1) {
            throw new Exception('该账号已被锁定');
        }
        $user['access_token'] = $accessToken;
        $user['upload_token'] = $this->userService->getUploadToken($user['id']);

        $appId = $this->siteConfigService->getValueByCode('weixin_mp_app_id');
        $userPlatform = $this->userPlatformService->getByUserIdWithAppid($appId, $user['id']);
        $user['openid'] = $userPlatform ? $userPlatform['open_id'] : '';
        if($userPlatform && $userPlatform['is_subscribed'] == 1) {
            $user['subscribe'] = true;
        } else {
            $user['subscribe'] = false;
        }

        $member = $this->memberProfileService->getByUserId($user['id']);
        $member = $this->memberProfileService->format($member);

        $user['gomessage_uid'] = $this->goMessageLogic->genUid($user['id']);

        return $this->success(['user' => $user, 'member' => $member]);
    }

    public function logout(Request $request)
    {
        $request = request();
        $accessToken = $request->header('access-token');
        $this->userService->logout($accessToken);
        return $this->success();
    }

    public function register_by_wx_user_info(Request $request)
    {
        $mobile = $request->param('mobile');
        $captcha = $request->param('sms_captcha');
        if(!check_mobile($mobile)) {
            throw new Exception('手机号错误');
        }
        if(!$this->smsLogic->verifyCaptcha('register', $mobile, $captcha)) {
            throw new Exception('短信验证码错误');
        }
        $fromuid = $request->param('fromuid', 0, 'intval');
        $openid = $request->param('openid', '');
        $nickname = $request->param('nickname', '');
        $headimgurl = $request->param('headimgurl', '');
        $unionid = $request->param('unionid', '');
        $wxUserInfo = [
            'openid' => $openid,
            'nickname' => $nickname,
            'headimgurl' => $headimgurl,
            'unionid' => $unionid
        ];

        $user = $this->userService->registerByWxAuthWithMobile($mobile, $fromuid, $wxUserInfo);

        $userDto = $this->userService->loginByOpenid($openid);
        $userDto['openid'] = $openid;

        $appId = $this->siteConfigService->getValueByCode('weixin_mp_app_id');
        $userPlatform = $this->userPlatformService->getByUserIdWithAppid($appId, $userDto['id']);
        if($userPlatform && $userPlatform['is_subscribed'] == 1) {
            $userDto['subscribe'] = true;
        } else {
            $userDto['subscribe'] = false;
        }

        $member = $this->memberProfileService->getByUserId($userDto['id']);
        $member = $this->memberProfileService->format($member);

        $userDto['gomessage_uid'] = $this->goMessageLogic->genUid($userDto['id']);

        return $this->success([
            'user' => $userDto,
            'member' => $member
        ]);
    }
}